<template>
  <el-row :gutter="24">
    <el-col :span="16">
      <el-form
        :inline="true"
        :rules="rules"
        ref="ruleForm"
        :model="system_right.groups[dataId]"
      >
        <el-form-item label="权限组名称" prop="groupsName">
          <el-input
            v-model="system_right.groups[dataId].groupsName"
            placeholder="权限组名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序值" prop="groupsSort">
          <el-input
            v-model.number="system_right.groups[dataId].groupsSort"
            placeholder="排序值越大越靠前"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addTab(editableTabsValue)"
            >保存</el-button
          >
          <el-button type="primary" @click="delTab(editableTabsValue)"
            >删除</el-button
          >
        </el-form-item>
      </el-form>
      <el-col :span="24">
        <el-tabs class="table-form-detail" type="border-card">
          <el-tab-pane v-for="item in system_right.menuList">
            <span slot="label">{{ item.menuName }}</span>
            <el-checkbox-group v-model="checkList">
              <div v-for="e in item.children">
                <p v-if="!e.hidden" class="tablemenu-title">
                  <el-checkbox
                    :label="e.id"
                    @change="i => handleCheckAllChange(i, e.id)"
                    >{{ e.menuName }}</el-checkbox
                  >
                </p>

                <div v-if="!e.hidden" class="checkbox-menu">
                  <el-checkbox v-for="i in e.children" :label="i.id">{{
                    i.menuName
                  }}</el-checkbox>
                </div>
              </div>
            </el-checkbox-group>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-col>
    <el-col :span="8">
      <el-col :span="24" class="table-form-approve">
        <div>
          <p>权限组内账号</p>
          <h-table-list
            border
            type="local"
            :data="chooseRecords"
            :columns="columns"
            :form-options="formOptions"
            :show-pagination="false"
            @select="selectRows"
          >
            <template slot="operate-column" slot-scope="scope">
              <el-button @click="() => removeThis(scope.row)">移除</el-button>
            </template>
          </h-table-list>

          <!-- <TableAndButton
              list-loading="listLoading"
              :table-data="list"
              sort-change="sortChange"
              show-reviewer="false"
              :column-data="data.tableColumn"
              :operateButton="false"
            /> -->
        </div>
      </el-col>
    </el-col>
  </el-row>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  props: ["dataId", "keyId"], //dataId为数组匹配顺序 keyId为主键获取更新值
  data() {
    return {
      checkList1: [],
      rules: {
        groupsName: [
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        groupsSort: [
          { type: "number", message: "数字", trigger: "blur" },
          {
            type: "number",
            min: 0,
            max: 999,
            message: "长度在 1 到 3 个字符",
            trigger: "blur"
          }
        ]
      },
      formOptions: {
        showSearchBtn: false,
        showResetBtn: false,
        changevalue: e => {
          console.log(e);
          const data = [];
          e.userName.forEach(item => {
            data.push(JSON.parse(item));
          });
          this.chooseRecords = data;
        },

        forms: [
          {
            prop: "userName",
            label: "添加用户",
            itemType: "select",
            itemWidth: "300",
            multiple: true,
            collapseTags: true,
            defaultValue: [],
            options: [{ value: "A", label: "A" }]
          }
        ]
      },
      columns: [
        { prop: "realName", label: "姓名", minWidth: "80" },
        { prop: "positionsName", label: "职位", minWidth: "80" },
        { prop: "operate", label: "操作", slotName: "operate-column" }
      ],
      menu1: true,
      editableTabsValue: "2",
      checkList: [],
      checkList1: [],
      editableTabs: [
        {
          title: "Tab 1",
          name: "1",
          content: "Tab 1 content"
        },
        {
          title: "Tab 2",
          name: "2",
          content: "Tab 2 content"
        }
      ],

      chooseRecords: [] // 当前权限组选择的用户
    };
  },
  mounted() {
    setTimeout(() => {
      this.getRoleList();
    }, 500);

    console.log("dataId", this.keyId);

    //通过dataId关联数组,keyId请求菜单权限得checkList
    this.loadInfo();
  },
  computed: {
    ...mapState(["system_right", "app"])
  },
  methods: {
    handleCheckAllChange(i, val) {
      console.log(this.$store.state.system_right.menuList);
      let items = [];
      //这个地方找到合适的数值后跳出循环
      for (let item of this.$store.state.system_right.menuList) {
        if (item.children) {
          for (let e of item.children) {
            if (e.id == val) {
              items = e;
              break;
            }
          }
        }
      }
      //得到选中数值的按钮组
      items = items.children.map(e => {
        return e.menuId;
      });
      if (i) {
        //选中

        this.checkList = [...this.checkList, ...items];

        this.checkList = Array.from(new Set(this.checkList));
      } else {
        //反选
        //checkList.filter((x) => !items.some((e) => arr.indexOf(x) === e));
        // this.checkList.push(items)

        console.log(this.checkList);
        this.checkList = this.checkList.filter(e => {
          return items.indexOf(e) == -1;
        });
      }
      console.log(this.checkList);
    },
    getRoleList() {
     
      this.$set(
        this.formOptions.forms[0],
        "options",
        this.$store.state.system_right.roleList
      );
    },
    loadInfo() {
      //权限数据回填
      this.$store
        .dispatch("system_right/requestRightMenuList", this.keyId)
        .then(res => {
          this.checkList = res
            ? res.data.map(e => {
                return e.menuId;
              })
            : [];
          console.log("checkList", this.checkList);
        });
      //权限组账号数据回填
      this.$store
        .dispatch("system_right/requestRightUserList", this.keyId)
        .then(res => {
          console.log("userList", res);
          //一个是表格回填，一个是选择框回填
          //this.forms[0].defaultValue=[1,2]//res.data
          const userName = res
            ? res.data.map(e => {
                return e.userId;
              })
            : [];
          // TODO - defaultValue 设置不起作用
          this.formOptions.forms[0].defaultValue = userName;

          this.chooseRecords = res ? res.data : [];
        });
    },
    addTab() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          const ids = this.chooseRecords.map(e => {
            return e.userId;
          });

          const param = {
            groupsName: this.$store.state.system_right.groups[this.dataId]
              .groupsName,
            groupsSort: this.$store.state.system_right.groups[this.dataId]
              .groupsSort,
            resourceIds: this.checkList,
            userIds: ids,
            id: this.keyId
          };
          this.$store.dispatch("system_right/saveGroups", param);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    delTab() {
      this.$confirm(`确认删除？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          console.log(this.keyId, "keyid+++");

          this.$store.dispatch("system_right/delGroups", {
            id: this.keyId,
            groups: this.$store.state.system_right.groups
          });
          this.$emit("getRightGroups");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    removeThis(row) {
      const userList = this.chooseRecords.filter(e => {
        // if (e.userId != args.userId) {
        //     return e
        // }
        return e.userId != row.userId;
      });
      // TODO - 此处无法响应式修改多选框中的值
      this.chooseRecords = userList;
    }
  }
};
</script>
<style lang="scss">
.tablemenu-title {
  border-bottom: 2px solid #e4e4e4;
}
.checkbox-menu {
  height: 60px;
  padding: 5px;
  background: #e4e4e4;
}
</style>
